import {CSSProperties, useCallback, useRef} from "react";
import {debounce} from "lodash";
import {Stall} from '@/components/stall';
import {ScrollView} from "@tarojs/components";
import styles from './index.module.scss';

interface Props{
  onPulDown: ()=>void;
  style?: CSSProperties;
}

export function List(props: Props){

  const isScrolling = useRef(false);
  const touchStartY = useRef(0);

  // eslint-disable-next-line react-hooks/exhaustive-deps
  const onScrollEnd = useCallback(debounce(()=>{
    isScrolling.current = false;
  }, 600), []);

  const onScroll = useCallback(()=>{
    isScrolling.current = true;
    onScrollEnd();
  },[onScrollEnd]);

  const handleTouchStart = useCallback((event: any) => {
    touchStartY.current = event.touches[0].pageY;
  }, []);

  const handleTouchEnd = useCallback((event: any)=>{
    if(isScrolling.current) return;
    const touchEndY = event.changedTouches[0].pageY;
    if(touchStartY.current < touchEndY){
      props.onPulDown();
    }
  }, [props]);

  return (
    <ScrollView
      scrollY
      enhanced
      bounces={false}
      style={props.style}
      className={styles.list}
      onScroll={onScroll}
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
    >
      <Stall />
      <Stall />
      <Stall />
      <Stall />
      <Stall />
      <Stall />
      <Stall />
      <Stall />
    </ScrollView>
  );
}
